package teamdamn.model;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Holds Login information and verifies that a username and password are correct.
 * 
 * @author Joel Hunsaker
 * @version Nov 20, 2014
 */
public final class Login {

    /** A map of Usernames to Passwords. */
    private Map<String, char[]> adminUsersAndPasswords;
    private Map<String, char[]> analystUsersAndPasswords;
    
    
    /**
     * Contructs a Login object.
     */
    public Login() {
        adminUsersAndPasswords = new HashMap<String, char[]>();
        analystUsersAndPasswords = new HashMap<String, char[]>();
        
        char[] adminPass = {'p','a','s','s'};
        char[] analPass = {'p','a','s','s','w','o','r','d'};
        adminUsersAndPasswords.put("Admin", adminPass);
        analystUsersAndPasswords.put("Analyst", analPass);
        analystUsersAndPasswords.put("a", new char[]{'a'});
        adminUsersAndPasswords.put("a", new char[]{'a'});
    }
    
    /**
     * Verifies that a username and login are valid for logging in.
     * 
     * @author joelhun
     * @param username  The username provided
     * @param password  The password provided
     * @param role      The user role provided
     * @return True: The username and password exist and are correct. False: They are not.
     */
    public boolean verifyLogin(String username, char[] givenPassword, String role) {
        // if role = admin, check admin map: user = key, pass = value
        if (username.length() < 1 || givenPassword == null) return false;
   
        if (role.equals("Admin")) {
            if (adminUsersAndPasswords.containsKey(username)) { //username exists
                char[] actualPassword = adminUsersAndPasswords.get(username);
                if (actualPassword != null) 
                    return Arrays.equals(actualPassword, givenPassword);   // user correct, is the password?
                else return false;
            } else return false; //username didn't exist with role
            
        } else {
            if (analystUsersAndPasswords.containsKey(username)) { //username exists
                char[] actualPassword = analystUsersAndPasswords.get(username);
                if (actualPassword != null) {
                    return Arrays.equals(actualPassword, givenPassword); //username correct, is the password?
                } else return false;
            } else return false; //username didn't exist with role
        }
      
    }
}
